/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import gui.multimedia.MultimediaView;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import technical.ClInit;

/**
 * This class is the main window of application
 *
 * @author thomas
 * Modifié le 11.05.2012 par Tania (ClInit)
 */
public final class MainWindow extends JFrame implements ActionListener, WindowListener {

    private static final long serialVersionUID = -4396859830906644269L;
    
    /* * * * * * DEFAULT PROPERTIES * * * * * */
    
    private static ClInit initialisations;
    
    private int _width = ClInit.getMainWidth();
    private int _height = ClInit.getMainHeight();
    private String _initialModule = ClInit.getMainInitialModule();
    private String _title = ClInit.getMainTitle();
    
    /* * * * * * MODULES MANAGEMENT * * * * * */
    
    private AbstractModule _myActiveModule = null;
    private HashMap<String, AbstractModule> _myModules = new HashMap<String, AbstractModule>();
    
    /* * * * * MENU BAR * * * * * */
    
    private JMenuBar _menuBar;
            
    /* FILE MENU */
    
    private JMenuItem _itemNewPage;
    private JMenuItem _itemAddToFavorites;
    private JMenuItem _itemDeleteAllHistory;
    private JMenuItem _itemCloseApplication;
    
    /* EDIT MENU */
    
    /* VIEW MENU */
    private ArrayList<JRadioButtonMenuItem> _chkModules = new ArrayList<JRadioButtonMenuItem>();
    
    /* ABOUT MENU */

    public static void main(String[] args) {
        
        // Instance de la classe ClInit, contenant les infos sur les chemins des fichiers
        initialisations = new ClInit();
        try {
            ClInit.initializeHibernateConf();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Launch this program with a new thread
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainWindow();
            }
        });
        
        // Nice salutations when you launch nemar in a terminal -> java -jar nemar.jar
        System.out.println("  _   _   U_____ u  __  __      _       ____     ");
        System.out.println(" | \\ |\"|  \\| ___\"|/U|' \\/ '|uU  /\"\\  uU |  _\"\\ u  ");
        System.out.println("<|  \\| |>  |  _|\"  \\| |\\/| |/ \\/ _ \\/  \\| |_) |/  ");
        System.out.println("U| |\\  |u  | |___   | |  | |  / ___ \\   |  _ <    ");
        System.out.println(" |_| \\_|   |_____|  |_|  |_| /_/   \\_\\  |_| \\_\\   ");
        System.out.println(" ||   \\\\,-.<<   >> <<,-,,-.   \\\\    >>  //   \\\\_  ");
        System.out.println(" (_\")  (_/(__) (__) (./  \\.) (__)  (__)(__)  (__) ");
        System.out.println("Bienvenue sur l'application NEMAR, parce que quand t'en as marre, NEMAR !");
    }

    public MainWindow() {
        
        build();
        changeModule(_initialModule);
        setVisible(true);
        
        this.addWindowListener(this);
    }

    /**
     * Build the skelet of frame
     */
    private void build() {

        setTitle(_title);
        setSize(_width, _height);

        // Position of frame is the center of screen
        setLocationRelativeTo(null);

        // Add close evenement
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Set the icon of application
        //setIconImage(new ImageIcon("connect.png").getImage());
        
        addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println("Echap || Ctrl + Q");
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE || e.getModifiers() == InputEvent.CTRL_MASK && e.getKeyCode() == KeyEvent.VK_Q) { 
                   System.exit(0);
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
        
        
        // Build the menu bar
        buildMenuBar();
        getApplicationState();
    }

    /**
     * Build the menu bar
     */
    private void buildMenuBar() {

        _menuBar = new JMenuBar();
        
        
        /* * * * * * FILE MENU * * * * * */
        
        JMenu menuFile = new JMenu("Fichier");
        
        _itemNewPage = new JMenuItem("Nouvelle page");
        _itemAddToFavorites = new JMenuItem("Ajouter aux favoris");
        _itemDeleteAllHistory = new JMenuItem("Effacer l'historique");
        _itemCloseApplication = new JMenuItem("Quitter");
        
        _itemNewPage.addActionListener(this);
        _itemAddToFavorites.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                if (_myActiveModule instanceof NavigatorView) {
                    System.out.println("Ajout aux favoris de la page courante");
                    NavigatorView navigator = (NavigatorView) _myActiveModule;
                    
                    navigator._vectorFavorites.add(navigator.getSelectedBrowser().getCurrentLocation());
                    if (navigator._favoritesList != null) {
                        navigator._favoritesList.setListData(navigator._vectorFavorites);
                        navigator._favoritesList.repaint();
                    }
                }
                
            }
        });
        _itemDeleteAllHistory.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (_myActiveModule instanceof NavigatorView) {
                    System.out.println("Historique efface");
                    NavigatorView navigator = (NavigatorView) _myActiveModule;
                    
                    try {
                        PrintWriter printwriter = new PrintWriter(new FileOutputStream("history.txt"));
                        printwriter.print("");
                        printwriter.close();
                        navigator._vectorHistory.removeAllElements();
                    }
                    catch (Exception ex) {
                        System.out.println("Error clear file history.txt");
                    }
                }
            }
        });
        _itemCloseApplication.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                exit();
            }
        });
        
        menuFile.add(_itemNewPage);
        menuFile.add(_itemAddToFavorites);
        menuFile.add(_itemDeleteAllHistory);
        menuFile.add(_itemCloseApplication);
        
        _menuBar.add(menuFile);
        
        /* * * * * * EDIT MENU * * * * * */
        
        JMenu menuEdit = new JMenu("Édition");
        
        _menuBar.add(menuEdit);
        
        
        /* * * * * * VIEW MENU * * * * * */
        
        JMenu menuView = new JMenu("Affichage");
        
        ButtonGroup group = new ButtonGroup();
        
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("BROWSER","Navigateur Internet");
        map.put("FOLDER", "Explorateur de fichier");
        map.put("MULTIMEDIA","Lecteur multimédia");
        map.put("RSS", "Lecteur de flux RSS");
        
        for (Entry<String, String> entry : map.entrySet()) {
            JRadioButtonMenuItem btn = new JRadioButtonMenuItem(entry.getValue());
            btn.setActionCommand(entry.getKey());
            btn.addActionListener(this);
            _chkModules.add(btn);
            group.add(btn);
            menuView.add(btn);
        }
        
        _menuBar.add(menuView);
        
        /* * * * * * OPTION MENU * * * * * */
        
        JMenu menuOptions = new JMenu("Options");
        
        JMenuItem btnPref = new JMenuItem("Préférences");
        btnPref.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new PreferencesView();
            }
        });
        menuOptions.add(btnPref);
        
        _menuBar.add(menuOptions);
        
        /* * * * * * ABOUT MENU * * * * * */
        
        JMenu menuAbout = new JMenu("À propos");

//        menuAbout.add(new JMenuItem("Aide"));
//        menuAbout.addSeparator();
        
        JMenuItem itemAbout = new JMenuItem("À propos");
        itemAbout.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, 
                    "<html>Cette application a été réalisée dans le cadre d'un projet JAVA\n"
                    + "du cursus de 4 étudiants en école d'ingénieur.\n\n"
                    + "o Laetitia Courant          <laetitia.courant@gmail.com>\n"
                    + "o Michael Rose              <rose.michael.william@gmail.com>\n"
                    + "o Tania Mathern             <tania.mathern@gmail.com>\n"
                    + "o Thomas Fritsch            <thomas.fritsch68@gmail.com>\n\n"
                    + "Have fun sur Nemar, et n'oubliez pas : Quand y en a marre, il y a NEMAR !", 
                    "A propos de nous", 
                    JOptionPane.INFORMATION_MESSAGE);
            } 
        });
        menuAbout.add(itemAbout);
        
        _menuBar.add(menuAbout);

        setJMenuBar(_menuBar);
    }

    /**
     * Change active module of application
     *
     * @param moduleName       Name of the module to switch on
     */
    public void changeModule(String moduleName) {

        AbstractModule module = null;

        System.out.println("GO " + moduleName + " !!");

        module = getModule(moduleName);

        if (module != null) {
            if (_myActiveModule != null) {
                _myActiveModule.setVisible(false);
            }

            _myActiveModule = module;
            setContentPane(_myActiveModule);
            _myActiveModule.setVisible(true);
        }
        
        // Update menu bar
        getApplicationState();
        
        for (JRadioButtonMenuItem chk : _chkModules) {
            if (chk.getActionCommand().equals(moduleName))
                chk.setSelected(true);
        }
    }
    
    /**
     * Return a module view
     * @param moduleName    Permit to select a module
     */
    public AbstractModule getModule(String moduleName) {
        
        AbstractModule module = null;
        
        if (_myModules.containsKey(moduleName)) {
            module = _myModules.get(moduleName);

        } else {

            if (moduleName.equals("BROWSER")) {
                module = new NavigatorView(this);
            } else if (moduleName.equals("MULTIMEDIA")) {
                module = new MultimediaView(this);
            } else if (moduleName.equals("FOLDER")) {
                module = new FileExplorerView(this);
            } else if (moduleName.equals("RSS")) {
                module = new RSSReaderView(this);
            }
            
            _myModules.put(moduleName, module);
        }
        
        return module;
    }

    /*
     * Return the menu state depends of the active module
     */
    private void getApplicationState() {
        
        if (_myActiveModule instanceof NavigatorView) {
            _itemNewPage.setVisible(true);
            _itemAddToFavorites.setVisible(true);
            _itemDeleteAllHistory.setVisible(true);
            _itemCloseApplication.setVisible(true);
        }
        else {
            _itemNewPage.setVisible(false);
            _itemAddToFavorites.setVisible(false);
            _itemDeleteAllHistory.setVisible(false);
            _itemCloseApplication.setVisible(true);
        }
    }
    
    /**
     * Exit function, it's here we save datas or anything else
     */
    private void exit() {
        
        // Save the favorites
        /**************************************************************************/
        BufferedWriter bwFavorites = null;
        try {
            bwFavorites = new BufferedWriter(new FileWriter("favorites.txt"));
            for (String favorite : NavigatorView._vectorFavorites) {
                bwFavorites.write(favorite + "\n");
            }
            bwFavorites.close();
        }
        catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
        /**************************************************************************/
        
        // Save the history
        /**************************************************************************/
        BufferedWriter bwHistory = null;
        try {
            bwHistory = new BufferedWriter(new FileWriter("history.txt"));
            for (String history : NavigatorView._vectorHistory) {
                bwHistory.write(history + "\n");
            }
            bwHistory.close();
        }
        catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
        /**************************************************************************/
        
        System.exit(0);
    }
    
    @Override
    public void actionPerformed(ActionEvent ae) {
        
        if (ae.getActionCommand().equalsIgnoreCase("Nouvelle page")) {
            if (_myActiveModule instanceof NavigatorView) {
                
                System.out.println("Nouvelle page du navigateur");
                NavigatorView navigator = (NavigatorView) _myActiveModule;
                navigator.addTab(ClInit.getBrowserDefaultHomePage());
            }
        }
        else {
            changeModule(ae.getActionCommand());
        }
    }

    @Override
    public void windowOpened(WindowEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowClosing(WindowEvent e) {
        exit();
    }

    @Override
    public void windowClosed(WindowEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowIconified(WindowEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowActivated(WindowEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        //new UnsupportedOperationException("Not supported yet.");
    }
}
